package com.ruoyi.utils.scheduleTask;

import com.ruoyi.domain.vo.UserInfoVo;
import com.ruoyi.service.IUserCenterService;
import com.ruoyi.system.domain.Activity;
import com.ruoyi.system.domain.UserInfo;
import com.ruoyi.system.service.IUserInfoService;
import com.ruoyi.utils.TanpuhuiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
public class MultithreadScheduleTask {

    @Autowired
    private TanpuhuiUtils tanpuhuiUtils;

    @Autowired
    private IUserCenterService userCenterService;

    /**
     * 每隔5分钟执行一次，判断低碳活动是否结束，如果结算，并且活动奖励没有结算，则结算奖励
     * @throws InterruptedException
     */
    @Async
    @Scheduled(fixedDelay = 5 * 60 * 1000)  //间隔5分钟执行一次
    public void first() throws InterruptedException {
//        System.out.println("活动结算任务开始执行 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
        // 获取活动已结束，并且没有结算活动奖励的活动
        List<Activity> activityList = tanpuhuiUtils.getNoSettleActivityList();
//        System.out.println(activityList);
        // 结算活动奖励
        for (Activity activity : activityList) {
            tanpuhuiUtils.settleActivityReward(activity.getActivityId());
        }
    }

    /**
     * 每天24点执行一次，执行特定任务
     */
    @Async
    @Scheduled(cron = "0 0 0 * * ?")  // 每天24点执行
    public void dailyMidnightTask() {
        System.out.println("每天24点任务开始执行 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
        // 获取所有的用户列表
        List<UserInfoVo> userList = userCenterService.getUserList();
        for (UserInfoVo userInfo : userList) {
            // 更新用户的连续减碳时间
            tanpuhuiUtils.updateUserReductionTime(userInfo.getUserId());
        }
    }

}
